'use strict';

/* Controllers */
  // signin controller
app.controller('dashboardController', ['$scope', '$http', '$state', '$modal', 'user_info', 'modal_warning', 'toaster', function($scope, $http, $state, $modal, user_info, modal_warning, toaster) {
    $scope.d0_1 = [];
    $scope.xArr = [];
    $scope.maxTime = 20;
    $scope.showSpline=true;
    $scope.refreshChart=true;
    $scope.pack_listener = null;
    $scope.$watch("showSpline", function(){
        $scope.refreshChart=!$scope.refreshChart;
    });
    user_info.check($scope).then(function(){
        var chagePackListener = function(){
            $scope.pack_listener && $scope.pack_listener.close();
            $scope.pack_listener = null;
            $scope.pack_listener = new EventSource('/app/api/user/package/' + $scope.showPackIndex);
            $scope.pack_listener.addEventListener('pack',function(e){
                let data = JSON.parse(e.data);
                if(data) user_info.setSinglePack($scope.showPackIndex, data);
            });
            $scope.pack_listener.addEventListener('useLog',function(e){
                let data = JSON.parse(e.data);
                console.log(data.dataArr);
                $scope.d0_1 = data.dataArr;
                $scope.xArr = data.xArr;
                $scope.maxTime = data.max;
                $scope.refreshChart=!$scope.refreshChart;
            });
        };
        $scope.packUsePercent = 0;
        $scope.resetAppKey = function(){
            modal_warning.confirm("重置确认", "重置AppKey会影响到您代理的用户鉴权，请谨慎操作！", true).then(function(){
                $http.get('/app/api/user/resetAppKey')
                    .then(function(response) {
                        user_info.set(response.data.data);
                        $scope.userInfo = response.data.data;
                    }, function(x) {

                    });
            },function(){});

        };
        $scope.reset_phone = function(){
            var modalInstance = $modal.open({
                templateUrl: '/tpl/modal/set_phone.html',
                controller: 'dashboardController.reset.phone',
                size: null
            });
            modalInstance.result.then(function () {
                // console.log(userInfo,'---');
            }, function () {});
        };
        $scope.recharge = function(){
            var modalInstance = $modal.open({
                templateUrl: '/tpl/modal/recharge.html',
                controller: 'dashboardController.recharge',
                size: null
            });
            modalInstance.result.then(function (userInfo) {
            }, function (userInfo) {
            });
        };
        $scope.getPackage = function(){
            var modalInstance = $modal.open({
                templateUrl: '/tpl/modal/package.html',
                controller: 'dashboardController.package',
                size: null
            });
            modalInstance.result.then(function (userInfo) {
            }, function (userInfo) {
            });
        };
        $scope.$watch("showPackIndex", function(){
            if($scope.userPackList[$scope.showPackIndex] && $scope.userPackList[$scope.showPackIndex].useInfo){
                $scope.packUsePercent = $scope.userPackList[$scope.showPackIndex].useInfo.count/$scope.package[$scope.userPackList[$scope.showPackIndex].index].level[$scope.userPackList[$scope.showPackIndex].level_id].limit * 100;
            }
        });
        $scope.changeUserPack = function(i){
            $scope.showPackIndex += i;
            chagePackListener();
        };
        $scope.package = window.appInfo.package;
        $scope.showPackIndex = 0;
        chagePackListener();
        $scope.$on("$destroy", function() {
            $scope.pack_listener && $scope.pack_listener.close();
        });
        $scope.$on("update_user_info", function(e, userInfo) {
            $scope.userInfo = userInfo;
            $scope.$apply();
        });
        $scope.$on("update_user_pack_list", function(e, userPackList) {
            $scope.userPackList = userPackList;
            if($scope.userPackList[$scope.showPackIndex].useInfo){
                $scope.packUsePercent = $scope.userPackList[$scope.showPackIndex].useInfo.count/$scope.package[$scope.userPackList[$scope.showPackIndex].index].level[$scope.userPackList[$scope.showPackIndex].level_id].limit * 100;
            } else {
                $scope.packUsePercent = 0;
            }
            $scope.$apply();
        });
    });
}]);

app.controller('dashboardController.reset.phone', ['$scope', '$modalInstance', '$http', 'user_info', 'toaster', function($scope, $modalInstance, $http, user_info, toaster) {
    $scope.authError = null;
    $scope.readyForCode = false;
    // $scope.userInfo = userInfo;
    $scope.newInfo = {tel:"",code:""};

    $scope.getCode = function() {
        $scope.readyForCode = false;
        $scope.authError = null;
        var phoneReg=/^[1][3,4,5,7,8][0-9]{9}$/;
        if (!phoneReg.test($scope.newInfo.tel)) {
            $scope.authError = "您所填手机格式有误";
        } else {
            $http.get('/app/api/phone/code/' + $scope.newInfo.tel)
                .then(function(response) {
                    $scope.readyForCode = true;
                }, function(x) {
                    $scope.authError = x.data.message;
                });
        }
    };
    $scope.ok = function () {
        $http.post('/app/api/user/info', $scope.newInfo)
            .then(function(response) {
                window.appInfo.user.first = false;
                window.appInfo.user.tel = $scope.newInfo.tel.substr(0,3) + "****" + $scope.newInfo.tel.substr(7, 4);
                user_info.set(window.appInfo.user);
                $modalInstance.close();
                toaster.pop("success", "修改手机", "成功");
            }, function(x) {
                $scope.authError = x.data.message;
            });
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]);
app.controller('dashboardController.recharge', ['$scope', '$modalInstance', '$http', 'user_info', "toaster", function($scope, $modalInstance, $http, user_info, toaster) {
    $scope.authError = null;
    $scope.payment_step = 0;//生成订单
    $scope.payment_url = "";
    $scope.payment_listen_name = null;
    $scope.payment_listener = null;
    $scope.checkCouponMsg = "";
    $scope.info = {amount:null, couponCode:"", type:1};
    $scope.coupon = {deduct:0};
    $scope.checkCoupon = function(){

    };
    $scope.createPayment = function () {
        console.log($scope.info);
        // $modalInstance.close();
        $http.post('/app/api/user/payment/create', $scope.info)
            .then(function(response) {
                $scope.payment_step = 1;//确认支付
                $scope.payment_url = response.data.data.url;
                $scope.payment_listen_name = response.data.data.payment_event;
            }, function(x) {
                $scope.authError = x.data.message;
            });
    };
    $scope.waitPay = function(){
        if($scope.payment_listen_name){
            $scope.payment_listener = new EventSource('/app/api/user/payment/listen/' + $scope.payment_listen_name);
            $scope.payment_listener.addEventListener('wait',function(e){
                $scope.payment_step = 2;//等待支付
                $scope.$apply();
            });
            $scope.payment_listener.addEventListener('end',function(e){
                //支付成功则返回总余额
                let result = JSON.parse(e.data);
                switch(result.res){
                    case "success":
                        $scope.payment_step = 3;//支付成功
                        toaster.pop("success", "充值", "成功");
                        break;
                    case "error":
                        $scope.payment_step = 4;//支付失败
                        toaster.pop("error", "充值", "失败");
                        break;
                    case "timeout":
                        $scope.payment_step = 5;//等待超时
                        toaster.pop("error", "充值", "获取充值结果超时");
                        break;
                }
                user_info.get().then(function(data){
                    data.userInfo.money = result.money;
                    user_info.set(data.userInfo);
                    $http.post('/app/api/user/updateUserBalance', result.money)
                        .then(function(response) {
                            $scope.payment_listener.close();
                            delete $scope.payment_listener;
                            $modalInstance.close();
                        }, function(x) {
                            $scope.authError = x.data.message;
                        });
                });
            });
        } else {

        }
    };
    $scope.ok = function () {
        $modalInstance.close();
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]);
app.controller('dashboardController.package', ['$scope', '$modalInstance', '$http', 'user_info', 'toaster', function($scope, $modalInstance, $http, user_info, toaster) {
    $scope.authError = null;
    $scope.package = window.appInfo.package;
    $scope.selectIndex = 0;
    $scope.selectSubIndex = 0;
    $scope.changeIndex = function(index){
        $scope.selectIndex = index;
    };
    $scope.changeSubIndex = function(index){
        $scope.selectSubIndex = $scope.selectSubIndex + index;
    };
    $scope.buy = function(){
        $http.post('/app/api/package/buy', {pack:$scope.selectIndex, limit:$scope.selectSubIndex})
            .then(function(response) {
                console.log(response.data.data);
                user_info.set(response.data.data.userInfo);
                user_info.setPack(response.data.data.userPackList);
                toaster.pop("success", "购买套餐成功", "");
                $modalInstance.close();
            }, function(x) {
                toaster.pop("success", "购买套餐失败", x.data.message);
                $scope.authError = x.data.message;
            });
    };
    $scope.$watch("selectIndex", function(){
        $scope.currentPackage = $scope.package[$scope.selectIndex];
        $scope.selectSubIndex = 0;
        $scope.currentSubPackage = $scope.currentPackage.level[$scope.selectSubIndex];
    });
    $scope.$watch("selectSubIndex", function(){
        $scope.currentSubPackage = $scope.currentPackage.level[$scope.selectSubIndex];
    });
    $scope.ok = function () {
        $modalInstance.close();
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]);